from app import dBSession
from sqlalchemy import desc, asc
from app.Models.BaseModel import BaseModel
from sqlalchemy_serializer import SerializerMixin
from app.Vendor.Decorator import classTransaction
from app.Models.Model import Compound


class Compounds(Compound, BaseModel, SerializerMixin):
    def getOne(self, filters, order='id desc', field=()):
        res = dBSession.query(Compounds).filter(*filters)
        order = order.split(' ')
        if order[1] == 'desc':
            res = res.order_by(desc(order[0])).first()
        else:
            res = res.order_by(asc(order[0])).first()
        if res == None:
            return None
        if not field:
            res = res.to_dict()
        else:
            res = res.to_dict(only=field)
        return res

    def getList(self, filters, field=(), offset=0, limit=100):
        res = {}
        res['page'] = {}
        res['page']['count'] = dBSession.query(Compounds).filter(*filters).count()
        res['list'] = []
        res['page']['total_page'] = self.get_page_number(res['page']['count'], limit)
        res['page']['current_page'] = offset
        if offset != 0:
            offset = (offset - 1) * limit

        if res['page']['count'] > 0:
            res['list'] = dBSession.query(Compounds).filter(*filters)
            res['list'] = res['list'].order_by(Compounds.id.desc()).offset(offset).limit(limit).all()
            cpdInformations = {}
        if not field:
            res['list'] = [c.to_dict() for c in res['list']]
            for c in res['list']:
                # 输出的cpd格式是（x轴，y轴，cpdname，href，title）
                # 因为会出现多个cpd就需要用两层列表来储存
                if cpdInformations.__contains__(c['data_entry']):
                    cpds = cpdInformations[c['data_entry']]
                else:
                    cpds = []
                comps = c['data_coords'].split(",")
                comps = [int(i) for i in comps]
                comps.append(c['data_entry'])
                comps.append(c['href'])
                comps.append(c['title'])
                cpds.append(comps)
                cpdInformations[c['data_entry']] = cpds
        else:
            res['list'] = [c.to_dict(only=field) for c in res['list']]
            for c in res['list']:
                # 输出的cpd格式是（x轴，y轴，cpdname，href，title）
                # 因为会出现多个cpd就需要用两层列表来储存
                if cpdInformations[c['data_entry']] is not None:
                    cpds = cpdInformations[c['data_entry']]
                else:
                    cpds = []
                comps = c['data_coords'].split(",")
                comps = [int(i) for i in comps]
                comps.append(c['data_entry'])
                comps.append(c['href'])
                comps.append(c['title'])
                cpds.append(comps)
                cpdInformations[c['data_entry']] = cpds
        return cpdInformations
